(:
  A procedure to count various facet values by time of day
:)
declare boundary-space strip;
import module namespace
    jj = "http://kumquat.emse.fr/utilitaires"
    at "jjutils.xq" ;
    
declare namespace xcl = "urn:schemas-microsoft-com:office:spreadsheet";

declare function local:get-time-from-item($item as node()) as xs:time {
  let $millis := xs:integer($item/info[@name="time"]/time/date)
  let $date := xs:dateTime("1970-01-01T00:00:00")+xs:integer($millis) idiv 1000
  return xs:time($date)
}

declare function local:count-by-timeofday($items as node()*,
                                          $boundaries as xs:time*,
                                          $rowheader as xs:string) as node()*
{
  <item>{
    <info name="facet">{$rowheader}</info>,
	  for $i in (1 to fn:count($boundaries)-1)
	  let $begin := $boundaries[$i]
	  let $end := $boundaries[$i+1]
	  let $number := fn:count($items[local:get-time-from-item(.) ge $begin][local:get-time-from-item(.) lt $end])
	  return
	     <info name="from {$begin}">{$number}</info>                          
	  ,
	  <info name="total">{fn:count($items)}</info>
	}</item>
};

<display>{
let $t := $arguments[1]
let $facetarray := fn:tokenize($arguments[2],",")
let $times := for $string in fn:tokenize($arguments[3],",") return xs:time(fn:concat($string,':00'))
let $boundaries := (xs:time('00:00:00'),$times,xs:time('23:59:59.999'))
let $items := doc($t)/display/item
return
  (local:count-by-timeofday($items,$boundaries,'all'),
  for $facet in $facetarray
  let $facetvalues := for $info in $items/info[@name=$facet] return jj:get-text($info)
  let $dfacetvalues := fn:distinct-values($facetvalues)
  return
    for $facetvalue in $dfacetvalues
    let $selection := $items[jj:get-text(./info[@name=$facet])=$facetvalue]
    order by fn:count($selection) descending
    return
      local:count-by-timeofday($selection,$boundaries,$facetvalue)
  )     
}</display>
